package utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JdbcUtils {
    private static DruidDataSource dataSource;
    private static  ThreadLocal<Connection> coons=new ThreadLocal<Connection>();
    static {

        Properties properties=new Properties();
//        InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
        try {
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(inputStream);
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
//            System.out.println(dataSource.getConnection());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static Connection getConnection(){
        Connection conn=coons.get();

        if(conn==null){
            try {
                conn= dataSource.getConnection();

                coons.set(conn);

                conn.setAutoCommit(false);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return  conn;
    }


        public static void commitAndClose(){
            Connection connection=coons.get();
            if(connection!=null){
                try {
                    connection.commit();

                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }finally {
                    try {
                        connection.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
            coons.remove();
        }

    public static void rollbackAndClose(){
        Connection connection=coons.get();
        if(connection!=null){
            try {
                connection.rollback();

            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        coons.remove();
    }
//    public static  void close(Connection conn){
//        if(conn!=null){
//            try {
//                conn.close();
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }
//        }
//    }


}
